package com.jtask.core.tasks;

import java.util.List;

import roboguice.util.Ln;
import roboguice.util.RoboAsyncTask;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.tasks.Tasks;
import com.google.api.services.tasks.model.TaskList;
import com.jtask.AppConstants;
import com.jtask.mvp.view.Main;
import com.jtask.mvp.view.TasksActivity;

public class LoadTaskLists extends RoboAsyncTask<List<TaskList>> implements
		AppConstants {

	private final HttpTransport transport = new NetHttpTransport();
	private JsonFactory jsonFactory = new JacksonFactory();
	private String requestCode;

	public LoadTaskLists(Context context, String requestCode) {
		super(context);
		this.requestCode = requestCode;
	}

	@Override
	public List<TaskList> call() throws Exception {
		Ln.i("Loading tasklists");
		GoogleCredential credential = new GoogleCredential.Builder()
				.setTransport(transport).setJsonFactory(jsonFactory)
				.setClientSecrets(CLIENT_ID, CLIENT_SECRET).build();

		if (requestCode != null) {
			Ln.i("Loading tasklists using request code");
			GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(
					transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
					requestCode, REDIRECT_URL).execute();
			credential.setFromTokenResponse(response);
			Editor editPreferences = getContext().getSharedPreferences(
					JTASK_PREFERENCES, Context.MODE_PRIVATE).edit();
			editPreferences
					.putString(K_ACCESS_TOKEN, response.getAccessToken());
			editPreferences.putString(K_REFRESH_TOKEN,
					response.getRefreshToken());
			editPreferences.commit();

		} else {
			Ln.i("Loading tasklists using preferences");
			SharedPreferences sharedPreferences = getContext()
					.getSharedPreferences(JTASK_PREFERENCES,
							Context.MODE_PRIVATE);
			credential.setAccessToken(sharedPreferences.getString(
					K_ACCESS_TOKEN, ""));
			credential.setRefreshToken(sharedPreferences.getString(
					K_REFRESH_TOKEN, ""));
		}

		Tasks service = new Tasks.Builder(transport, jsonFactory, credential)
				.setApplicationName(APP_GNAME).build();
		Tasks.Tasklists.List taskListRequest = service.tasklists().list();
		taskListRequest.setFields(TASK_LIST_FIELDS);
		List<TaskList> taskList = taskListRequest.execute().getItems();
		Ln.i("Tasklists loadeds");
		return taskList;
	}

	@Override
	protected void onPreExecute() throws Exception {
		super.onPreExecute();
	}

	@Override
	protected void onSuccess(List<TaskList> t) throws Exception {

		TabHost taskListsTabHost = ((Main) getContext()).getTabHost();
		taskListsTabHost.setup(((Main) getContext()).getLocalActivityManager());
		for (TaskList tl : t) {
			TabSpec newTabSpec = taskListsTabHost.newTabSpec("new");
			newTabSpec.setIndicator(tl.getTitle());
			newTabSpec
					.setContent(new Intent(getContext(), TasksActivity.class));
			taskListsTabHost.addTab(newTabSpec);
		}
	}

}
